package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.mapper.CheckGroupDao;
import com.itheima.mapper.SetmealAndCheckGroup;
import com.itheima.mapper.SetmealDao;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private SetmealAndCheckGroup setmealAndCheckGroup;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        PageInfo<Setmeal> pageInfo = new PageInfo<>(setmealDao.findPage(queryPageBean.getQueryString()));
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    @Transactional
    public void addSetmeal(Setmeal setmeal, Integer[] checkgroupIds) {
        if (setmeal == null) {
            throw new RuntimeException("套餐信息不能为空");
        }
        if (checkgroupIds == null || checkgroupIds.length == 0) {
            throw new RuntimeException("套餐关联检查组不能为空");
        }

        //添加套餐
        setmealDao.addSetmeal(setmeal);

        //如果有上传图片 则保存到redis当中
        if (setmeal.getImg() != null && setmeal.getImg().length() > 0) {
            try {
                String imgUrl = setmeal.getImg();

                String imgName = extractFileNameFromUrl(imgUrl);

                log.info("数据库中的图片名称保存到redis当中:{}", imgName);
                redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES,imgName);
            } catch (Exception e) {
                log.error("图片上传失败: {}", e.getMessage(), e);
                throw new RuntimeException("图片上传失败，请稍后重试");
            }
        }

        //添加套餐和检查组的关联关系
        for (Integer checkgroupId : checkgroupIds) {
            setmealAndCheckGroup.addCheckItemAndCheckGroup(setmeal.getId(), checkgroupId);
        }
    }

    @Override
    public Setmeal findById(Integer id) {
        if (id == null || id <= 0) {
            throw new RuntimeException("套餐ID不能为空");
        }

        return setmealDao.findById(id);
    }

    @Override
    public void editSetmeal(Setmeal setmeal, Integer[] checkgroupIds) {
        if (setmeal == null) {
            throw new RuntimeException("套餐信息不能为空");
        }
        if (checkgroupIds == null || checkgroupIds.length == 0) {
            throw new RuntimeException("套餐关联检查组不能为空");
        }
        //修改套餐信息
        setmealDao.editSetmeal(setmeal);
        //先删除套餐和检查组的关联关系
        setmealAndCheckGroup.deleteBySetmealId(setmeal.getId());
        //再添加新的关联关系
        for (Integer checkgroupId : checkgroupIds) {
            setmealAndCheckGroup.addCheckItemAndCheckGroup(setmeal.getId(), checkgroupId);
        }
    }








    private String extractFileNameFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            throw new IllegalArgumentException("URL不能为空");
        }

        // 找到最后一个 '/' 的位置
        int lastIndex = url.lastIndexOf('/');

        // 如果找到了 '/'
        if (lastIndex != -1 && lastIndex < url.length() - 1) {
            return url.substring(lastIndex + 1); // 返回 '/' 后面的部分
        } else {
            throw new IllegalArgumentException("无效的URL格式，无法提取文件名");
        }
    }
}
